#!/bin/sh
#
# Simple script to generate iwd network files.

[ "$1" ] || {
    printf '%s\n' "usage: printf pass | ${0##*/} ssid" >&2
    exit 1
}

# Read the password from 'stdin'.
read -r pass; [ "$pass" ] || exit 1

# Consider all characters as single-byte.
export LC_CTYPE=C

# The SSID appears verbatim in the name if it contains
# only alphanumeric characters, spaces, underscores or
# minus signs. Otherwise it is encoded as an equal sign
# followed by the lower-case hex encoding of the name.
case $1 in
    *[!A-Za-z0-9_' '-]*)
        ssid="=$(printf %s "$1" | od -vA n -t x1 | tr -d '\n ')"
    ;;

    *)
        ssid=$1
    ;;
esac

printf '%s\n\n' "Save this output to /var/lib/iwd/$ssid.psk" >&2
printf '[Security]\n'
printf 'Passphrase=%s\n' "$pass"
printf '\nTIP: You can use this output directly as the\n' >&2
printf '     help messages are printed to stderr.\n' >&2
